package com.xxx.user.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;
import com.xxx.system.annotation.PreAuthorize;
import com.xxx.user.domain.User;
import com.xxx.user.query.UserQuery;
import com.xxx.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author BoWei Wang
 * @date 2025/8/5
 */

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口类")
public class UserController {
    @Autowired
    private IUserService userService;

    @GetMapping
    @ApiOperation("查询所有用户")
    public R<List<User>> findAll() {
        return R.ok(userService.findAll());
    }

    @GetMapping("/{id}")
    @ApiOperation("查询单个用户")
    public R<User> findOne(@PathVariable Long id) {
        return R.ok(userService.findOne(id));
    }

    @PostMapping
    @ApiOperation("分页条件查询用户")
    public PageInfo<User> queryPage(@RequestBody UserQuery userQuery) {
        List<User> users = userService.queryPage(userQuery);
        return new PageInfo<User>(users);
    }

    @PostMapping("/add")
    @ApiOperation("添加用户")
    public R<Void> addUser(@RequestBody User user) {
        userService.addUser(user);
        return R.ok();
    }

    @PutMapping
    @ApiOperation("新增修改用户")
    public R<Void> addOrUpdateUser(@RequestBody User user) {
        try {
            if (user.getId() == null) {
                userService.addUser(user);
            } else {
                userService.updateUser(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("用户名已存在!");
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    @PreAuthorize(name = "删除用户",sn="user:delete")
    public R<Void> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

    @PatchMapping
    @ApiOperation("批量删除用户")
    public R<Void> batchDeleteUsers(@RequestBody Long[] ids) {
        try {
            userService.batchDeleteUsers(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }

}
